package com.ruoyi.quartz.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.bizsys.domain.ExtIdentityResult;
import com.ruoyi.bizsys.service.IExtIdentityResultService;
import com.ruoyi.business.mapper.ExtIdentityMapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.extdata.common.config.OkraConfig;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component("okraRerun")
public class OkraTask {


    @Autowired
    IExtIdentityResultService iExtIdentityResultService;

    @Autowired
    ExtIdentityMapper extIdentityMapper;

    @Autowired
    OkraConfig okraConfig;

    @Resource
    private OkHttpClient okHttpClient;


    public void okraRerun(){

        Integer startLimit = 0;
        Integer endLimit = 1000;
        List<ExtIdentityResult> extIdentityResults = extIdentityMapper.getList(startLimit,endLimit);

        while (extIdentityResults.size()>0){

            for (int i = 0; i < extIdentityResults.size(); i++) {
                try {
                    ExtIdentityResult extIdentityResult1 = extIdentityResults.get(i);
                    ExtIdentityResult ccc = send(extIdentityResult1.getCustomer());
                    ccc.setId(extIdentityResult1.getId());
                    iExtIdentityResultService.updateExtIdentityResult(ccc);
                } catch (Exception e) {
                    log.error("OkraTask error", e);
                    continue;
                }
            }
            startLimit = endLimit;
            endLimit+=1000;
            extIdentityResults = extIdentityMapper.getList(startLimit,endLimit);

        }


    }

    private ExtIdentityResult send(String cust) throws Exception {
        // OkHttpClient client = new OkHttpClient();

        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "customer=" + cust);
        Request request = new Request.Builder()
                .url("https://api.okra.ng/v2/identity/getByCustomer")
                .post(body)
                .addHeader("Accept", "application/json; charset=utf-8")
                .addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MDhhNWU0MDYzODBhNTRhNmZlMTk4MDMiLCJpYXQiOjE2MTk2ODA4MzN9.cRY474pgxpXet8U-NsnWPt6C9CIOgDMqF_g9b8HvEh4")
                .addHeader("Authorization", "Bearer "+ okraConfig.getPrivateKey())
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        Response response = okHttpClient.newCall(request).execute();
        return getExtIdentityResult(new ExtIdentityResult(), JSONObject.parseObject(response.body().string()));
    }

    private ExtIdentityResult getExtIdentityResult(ExtIdentityResult extIdentifyResult, JSONObject apiRes) {

        if (apiRes == null || apiRes.getJSONObject("data") == null || apiRes.getJSONObject("data").getJSONArray("identity") == null || apiRes.getJSONObject("data").getJSONArray("identity").size() == 0) {
            return extIdentifyResult;
        }
        JSONObject identity = apiRes.getJSONObject("data").getJSONArray("identity").getJSONObject(0);

        if (identity != null && identity.size() > 0) {
            if(StringUtils.isNotBlank(identity.getString("firstname"))){
                extIdentifyResult.setFirstname(identity.getString("firstname"));
            }
            if(StringUtils.isNotBlank(identity.getString("middlename"))){
                extIdentifyResult.setMiddlename(identity.getString("middlename"));
            }
            if(StringUtils.isNotBlank(identity.getString("gender"))){
                extIdentifyResult.setGender(identity.getString("gender"));
            }
            if(StringUtils.isNotBlank(identity.getString("lastname"))){
                extIdentifyResult.setLastname(identity.getString("lastname"));
            }
            if(StringUtils.isNotBlank(identity.getString("dob"))){
                extIdentifyResult.setDob(identity.getString("dob"));
            }
            if(StringUtils.isNotBlank(identity.getString("fullname"))){
                extIdentifyResult.setFullname(identity.getString("fullname"));
            }
            if(StringUtils.isNotBlank(identity.getString("bvn"))){
                extIdentifyResult.setBvn(identity.getString("bvn"));
            }

            JSONArray phoneArray = identity.getJSONArray("phone");
            if (phoneArray.size() > 0) {
                extIdentifyResult.setPhone1(phoneArray.getString(0));
                if (phoneArray.size() > 1) {
                    extIdentifyResult.setPhone2(phoneArray.getString(1));
                }
                List<String> phoneList = phoneArray.toJavaList(String.class);
                String phones = phoneList.stream().collect(Collectors.joining(","));
                extIdentifyResult.setPhones(phones);
            }

        }
        return extIdentifyResult;
    }

}
